import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/auth.config';
import { prisma } from '@/lib/prisma';
import { NextResponse } from 'next/server';
import { revalidatePath } from 'next/cache';

// 删除行程
export async function DELETE(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user) {
      return new NextResponse('Unauthorized', { status: 401 });
    }

    const trip = await prisma.trip.findUnique({
      where: { id: params.id },
    });

    if (!trip) {
      return new NextResponse('Trip not found', { status: 404 });
    }

    if (trip.userId !== session.user.id) {
      return new NextResponse('Forbidden', { status: 403 });
    }

    // 删除行程及其相关数据
    await prisma.trip.delete({
      where: { id: params.id },
    });

    return new NextResponse(null, { status: 204 });
  } catch (error) {
    console.error('Delete trip error:', error);
    return new NextResponse('Internal error', { status: 500 });
  }
}

// 更新行程的部分字段（如公开状态）
export async function PATCH(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user) {
      return new NextResponse('Unauthorized', { status: 401 });
    }

    const trip = await prisma.trip.findUnique({
      where: { id: params.id },
    });

    if (!trip) {
      return new NextResponse('Trip not found', { status: 404 });
    }

    if (trip.userId !== session.user.id) {
      return new NextResponse('Forbidden', { status: 403 });
    }

    const body = await request.json();
    const updatedTrip = await prisma.trip.update({
      where: { id: params.id },
      data: {
        isPublic: body.isPublic,
      },
    });

    return NextResponse.json(updatedTrip);
  } catch (error) {
    console.error('Update trip error:', error);
    return new NextResponse('Internal error', { status: 500 });
  }
}

// PUT 方法保持不变，用于完整更新行程
export async function PUT(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      return NextResponse.json({ error: '请先登录' }, { status: 401 });
    }

    const trip = await prisma.trip.findUnique({
      where: { id: params.id },
    });

    if (!trip) {
      return NextResponse.json({ error: '行程不存在' }, { status: 404 });
    }

    if (trip.userId !== session.user.id) {
      return NextResponse.json({ error: '无权限修改此行程' }, { status: 403 });
    }

    const body = await request.json();

    // 使用事务更新行程和活动
    const updatedTrip = await prisma.$transaction(async (tx) => {
      // 删除现有活动
      await tx.activity.deleteMany({
        where: { tripId: params.id },
      });

      // 更新行程和创建新活动
      return tx.trip.update({
        where: { id: params.id },
        data: {
          title: body.title,
          description: body.description,
          startDate: new Date(body.startDate),
          endDate: new Date(body.endDate),
          isPublic: body.isPublic,
          activities: {
            create: body.activities.map((activity: any) => ({
              title: activity.title,
              description: activity.description,
              date: new Date(activity.date),
            })),
          },
        },
        include: {
          activities: true,
        },
      });
    });

    // 重新验证路径
    revalidatePath('/trips');
    
    return NextResponse.json(updatedTrip);
  } catch (error: any) {
    console.error('Update trip error:', error);
    return NextResponse.json(
      { error: '更新行程失败', details: error.message },
      { status: 500 }
    );
  }
} 